/** *******************************************************************
 * FlexDatabaseManager
 * @author  Jonnie Spratley
 * @contact jonniespratley@gmail.com
 * @internal
 ******************************************************************* */
package com.jonniespratley.flexdatabasemanager.commands.tables
{
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	import com.jonniespratley.flexdatabasemanager.business.FlexDatabaseManagerDelegate;
	import com.jonniespratley.flexdatabasemanager.events.tables.UpdateRecordEvent;
	import com.jonniespratley.flexdatabasemanager.model.ModelLocator;
	import com.jonniespratley.flexdatabasemanager.vo.*;
	
	import mx.controls.Alert;
	import mx.rpc.IResponder;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;

	public class UpdateRecordCommand implements ICommand, IResponder
	{
		private var model:ModelLocator = ModelLocator.getInstance();

		public function execute( event:CairngormEvent ) : void
		{
			model.interactingWithServer = true;
			
			var evt:UpdateRecordEvent = event as UpdateRecordEvent;
			var delegate:FlexDatabaseManagerDelegate = new FlexDatabaseManagerDelegate( this );
			
			if ( model.selectedDatabase == null && model.selectedTable == null )
			{
				Alert.show( 'Please select a database and/or table' );
				return;
				
			} else {
				model.interactingWithServer = true;
				delegate.updateRecord( model.currentUser, model.selectedDatabase, model.selectedTable, evt.aQuery );
			}

		}

		public function result( data:Object ) : void
		{
			model.interactingWithServer = false;
			
			var result:ResultEvent = data as ResultEvent;
			model.globalStatusMessage = data.result;
			//Alert.show( data.result );
			
		}

		public function fault( fault:Object ):void
		{
			model.interactingWithServer = false;
			
			var faultEvt:FaultEvent = fault as FaultEvent;
			Alert.show(faultEvt.fault.toString(), "Error");
			trace(faultEvt.fault.faultString);
		}

	}
}